package web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import dao.FollowDAO;
import dao.RestaurantDAO;

import beans.Follow;
import beans.Restaurant;
import beans.User;

@Controller
public class FollowController {
	private LoggedUser loggedUser;	
	private FollowDAO followDAO;
	private RestaurantDAO restaurantDAO;
	
	

	public void setRestaurantDAO(RestaurantDAO restaurantDAO) {
		this.restaurantDAO = restaurantDAO;
	}

	public void setFollowDAO(FollowDAO followDAO) {
		this.followDAO = followDAO;
	}

	public void setLoggedUser(LoggedUser loggedUser) {
		this.loggedUser = loggedUser;
	}
	
	@RequestMapping(value = "/followRestaurantId={restaurantId}")
	public ModelAndView follow(@PathVariable("restaurantId") int id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		User user = loggedUser.getLoggedUser();
		
		Follow follow = followDAO.findFollow(user);
		if(follow==null){
			follow = new Follow();
			follow.setRestaurant_id(id);
			follow.setUsername(user.getUsername());
			followDAO.saveFollow(follow);
		}
		else{
			Restaurant restaruant = restaurantDAO.findRestaurantByUser(user.getUsername());
			if(follow.getRestaurant_id()==id){
				follow.setRestaurant_id(id);
				followDAO.deleteFollow(follow);
			}
			else{
				follow.setRestaurant_id(id);
				followDAO.updateFollow(follow);
			}
			
		}
		return new ModelAndView("redirect:restaurantid="+id+".htm");
	}

}
